package com.exonline.controller.login;

import cn.hutool.core.util.IdUtil;
import com.exonline.commons.utils.TokenUtil;
import com.exonline.entity.Student;
import com.exonline.entity.Teacher;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc  登录
 * @author  jjr
 */
@WebServlet("/font/Login")
public class LoginServlet extends HttpServlet  {
    ObjectMapper mapper = new ObjectMapper();
    LoginService service = new LoginService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        try {
            if ("login".equals(method)) {
                this.login(req, resp);
            } else if ("register".equals(method)) {
                this.register(req, resp);
            } else if ("logout".equals(method)) {
                this.logout(req, resp);
            }
        }catch (Exception e){
            throw new ServletException(e);
        }
    }

    /**
     * @desc  注册
     * @param req
     * @param resp
     * @throws IOException
     */
    private void register(HttpServletRequest req, HttpServletResponse resp) throws IOException, NoSuchAlgorithmException {
        String id = IdUtil.simpleUUID();
        String sname = req.getParameter("sname");
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        System.out.println("sname:" + sname + "," + "phone:" + phone + "," + "password:" + password);
        Map<String, Object> map = new HashMap<>();
        int count = service.register(id, sname, phone, password);
        if (count != 0) {
            map.put("code", 200);
            map.put("msg", "注册成功");
            map.put("data", id);
            map.put("phone",phone);

            String token = TokenUtil.createToken(id, sname);
            map.put("token",token);
            mapper.writeValue(resp.getWriter(),map);

        }else {
            map.put("code", 201);
            map.put("msg", "注册失败,该用户名已经存在");
            map.put("data", phone);
            mapper.writeValue(resp.getWriter(), map);
        }
    }

    /**
     * @desc  登录
     * @param req
     * @param resp
     * @throws IOException
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, NoSuchAlgorithmException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        System.out.println("phone:" + phone + "," + "password:" + password);

        Map<String, Object> map = new HashMap<>();
        // 先以教师身份登录
        Teacher teacher = (Teacher) service.login(phone, password, "教师");
        if (teacher != null && teacher.getStatus().equals("1")) {
            // 教师状态为1（活跃），登录成功
            map.put("code", 200);
            map.put("msg", "登录成功");
            map.put("data", teacher);
            //Token
            String token = TokenUtil.createToken(teacher.getId(), teacher.getTname());
            map.put("token",token);
            mapper.writeValue(resp.getWriter(), map);

            return;
        }
        // 再以学生身份登录
        Student student = (Student) service.login(phone, password, "学生");
        if (student != null && student.getStatus().equals("1")) {
            // 学生状态为1（活跃），登录成功
            map.put("code", 200);
            map.put("msg", "登录成功");
            map.put("data", student);
            String token = TokenUtil.createToken(student.getId(), student.getSname());
            map.put("token",token);

            mapper.writeValue(resp.getWriter(), map);
            return;

        }
        map.put("code", 201);
        map.put("msg", "登录失败");
        map.put("data", null);
        mapper.writeValue(resp.getWriter(), map);
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) {

    }
}
